<template>
  <div class="page-container">
    <BridgeVerticalTabNav :bridge-id="bridgeIdFromRoute" />
    
    <div class="bridge-health-container">
      <!-- 顶部操作栏 -->
      <div class="operation-bar">
        <div class="left">
        <span>维护保养记录</span>
          <!-- <el-select
            v-model="currentPageValue"
            class="page-selector"
            @change="handlePageChange"
          >
            <el-option
              v-for="item in pageOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :class="{ 'is-active': item.value === currentPageValue }"
            />
          </el-select> -->
        </div>
        <div class="right">
          <el-button type="primary" @click="handleAdd" class="custom-button">
            <i class="el-icon-plus"></i> 新增数据
          </el-button>
          <!-- <el-button type="danger" @click="handleBatchDelete" class="custom-button">
            <i class="el-icon-delete"></i> 批量删除
          </el-button> -->
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        class="custom-table"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="bridgeId" label="桥梁名称">
          <template #default="{ row }">
            <span class="bridge-name">
              {{
                bridgeOptions.find((item) => item.value === Number(row.bridgeId))?.label ||
                row.bridgeName
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="maintenanceTime" label="维护时间" width="180" />
        <el-table-column prop="maintenanceUnit" label="维护单位名称" width="180" />
        <el-table-column prop="maintenanceContent" label="具体内容" min-width="200">
          <template #default="scope">
            <span class="ellipsis-text" @click="showContent(scope.row)">
              {{ (scope.row.maintenanceContent || "暂无内容").slice(0, 20) }}
              {{ scope.row.maintenanceContent?.length > 20 ? "..." : "" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="maintenanceCost" label="维护费用(万元)" width="150">
          <template #default="{ row }">
            {{ Number(row.maintenanceCost).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="maintenancePersonnel" label="人员信息" width="150" />
        <el-table-column label="备注" prop="remarks" min-width="120" align="center">
          <template #default="scope">
            <span class="ellipsis-text" @click="showRemarks(scope.row)">
              {{ (scope.row.remarks || "暂无备注").slice(0, 20) }}
              {{ scope.row.remarks?.length > 20 ? "..." : "" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleView(row)"
              class="operation-button"
            >
              详情
            </el-button>
            <el-button link @click="handleDelete(row)" class="operation-button danger">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          background
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="50%"
        class="custom-dialog"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="选择桥梁" prop="bridgeId">
            <el-select
              v-model="form.bridgeName"
              placeholder="请选择桥梁"
              style="width: 100%"
            >
              <el-option
                v-for="item in bridgeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="维护时间" prop="maintenanceTime">
            <el-date-picker
              v-model="form.maintenanceTime"
              type="datetime"
              placeholder="选择维护时间"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="维护单位名称" prop="maintenanceUnit">
            <el-input v-model="form.maintenanceUnit" placeholder="请输入维护单位名称" />
          </el-form-item>
          <el-form-item label="具体内容" prop="maintenanceContent">
            <el-input
              type="textarea"
              v-model="form.maintenanceContent"
              :rows="3"
              placeholder="请输入具体内容"
            />
          </el-form-item>
          <el-form-item label="维护费用" prop="maintenanceCost">
            <el-input
              v-model="form.maintenanceCost"
              placeholder="请输入维护费用(万元)"
              type="number"
              :precision="2"
              :step="0.01"
            >
              <template #append>万元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="人员信息" prop="maintenancePersonnel">
            <el-input v-model="form.maintenancePersonnel" placeholder="请输入人员信息" />
          </el-form-item>
          <el-form-item label="备注信息" prop="remarks">
            <el-input
              type="textarea"
              v-model="form.remarks"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 备注信息弹窗 -->
      <el-dialog v-model="remarksDialogVisible" title="备注信息" width="40%">
        <div style="white-space: pre-wrap">{{ currentRemarks }}</div>
        <template #footer>
          <span>
            <el-button @click="remarksDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 添加新的弹窗 -->
      <el-dialog v-model="issuesDialogVisible" title="发现的问题" width="40%">
        <div style="white-space: pre-wrap">{{ currentIssues }}</div>
        <template #footer>
          <span>
            <el-button @click="issuesDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog v-model="measuresDialogVisible" title="维护措施" width="40%">
        <div style="white-space: pre-wrap">{{ currentMeasures }}</div>
        <template #footer>
          <span>
            <el-button @click="measuresDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog v-model="reportDialogVisible" title="报告文件路径" width="40%">
        <div style="white-space: pre-wrap">{{ currentReport }}</div>
        <template #footer>
          <span>
            <el-button @click="reportDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 内容信息弹窗 -->
      <el-dialog v-model="contentDialogVisible" title="具体内容" width="40%">
        <div style="white-space: pre-wrap">{{ currentContent }}</div>
        <template #footer>
          <span>
            <el-button @click="contentDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getBridgeMaintenanceRecord,
  getBridgeMaintenanceRecordById,
  addBridgeMaintenanceRecord,
  updateBridgeMaintenanceRecord,
  deleteBridgeMaintenanceRecord,
} from "@/api/bridge/bisc/bridge";
import { getBridgeList } from "@/api/bridge/bisc/bridge";
import dayjs from "dayjs";
import { useRouter, useRoute } from "vue-router";
import BridgeVerticalTabNav from '../components/BridgeVerticalTabNav.vue';

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);

// 获取路由参数
const router = useRouter();
const route = useRoute();
const bridgeIdFromRoute = ref<string | null>(null);

// 页面选择相关
const currentPageValue = ref("maintenance");
const pageOptions = ref([
  { label: "桥梁健康数据", value: "health" },
  { label: "桥梁保养周期", value: "cycle" },
  { label: "维护保养记录", value: "maintenance" },
]);

// 页面跳转处理
const handlePageChange = (value: string) => {
  // 保持当前的bridgeId参数
  const query = bridgeIdFromRoute.value ? { bridgeId: bridgeIdFromRoute.value } : {};
  
  if (value === "cycle") {
    router.push({ path: '/basic-data/three-pages/bridge', query });
  } else if (value === "maintenance") {
    router.push({ path: '/basic-data/four-pages/bridge', query });
  } else if (value === 'health') {
    router.push({ path: '/basic-data/two-pages/bridge', query });
  }
};

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref();
const form = ref({
  id: "",
  bridgeId: "",
  bridgeName: "",
  maintenanceTime: "",
  maintenanceUnit: "",
  maintenanceContent: "",
  maintenanceCost: "",
  maintenancePersonnel: "",
  remarks: "",
});

// 备注弹窗相关
const remarksDialogVisible = ref(false);
const currentRemarks = ref("");

// 新添加的弹窗相关
const issuesDialogVisible = ref(false);
const measuresDialogVisible = ref(false);
const reportDialogVisible = ref(false);
const currentIssues = ref("");
const currentMeasures = ref("");
const currentReport = ref("");

// 添加桥梁列表相关的响应式变量
const bridgeOptions = ref([]);

// 表单校验规则
const rules = {
  bridgeId: [{ type: ['string', 'number'], required: true, message: "请选择桥梁", trigger: "change" }],
  maintenanceTime: [{ required: true, message: "请选择维护时间", trigger: "change" }],
  maintenanceUnit: [{ required: true, message: "请输入维护单位名称", trigger: "blur" }],
  maintenanceContent: [{ required: true, message: "请输入具体内容", trigger: "blur" }],
  maintenanceCost: [{ required: true, message: "请输入维护费用", trigger: "blur" }],
  maintenancePersonnel: [{ required: true, message: "请输入人员信息", trigger: "blur" }],
};

// 获取健康评分对应的标签类型
const getHealthScoreType = (score: number) => {
  if (score >= 80) return "success";
  if (score >= 60) return "warning";
  return "danger";
};

// 内容弹窗相关
const contentDialogVisible = ref(false);
const currentContent = ref("");

// 显示内容信息
const showContent = (row: any) => {
  currentContent.value = row.maintenanceContent || "暂无内容";
  contentDialogVisible.value = true;
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const params: any = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchQuery.value,
    };
    
    // 如果有桥梁ID参数，添加到查询条件
    if (bridgeIdFromRoute.value) {
      params.bridgeId = bridgeIdFromRoute.value;
    }
    
    const res = await getBridgeMaintenanceRecord(params);
    // 处理桥梁名称显示和时间格式化
    tableData.value = res.rows.map(item => ({
      ...item,
      bridgeName: bridgeOptions.value.find(bridge => bridge.value === item.bridgeId)?.label || item.bridgeName,
      maintenanceTime: item.maintenanceTime ? dayjs(item.maintenanceTime).format('YYYY-MM-DD HH:mm:ss') : '',
    }));
    total.value = res.total;
  } catch (error) {
    console.error("获取数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getList();
};

// 处理新增
const handleAdd = () => {
  dialogTitle.value = "新增数据";
  form.value = {
    id: "",
    bridgeId: bridgeIdFromRoute.value || "",
    bridgeName: "",
    maintenanceTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    maintenanceUnit: "",
    maintenanceContent: "",
    maintenanceCost: "",
    maintenancePersonnel: "",
    remarks: "",
  };
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row: any) => {
  try {
    const res = await getBridgeMaintenanceRecordById(row.id);
    form.value = {
      ...res.data,
      maintenanceTime: res.data.maintenanceTime ? dayjs(res.data.maintenanceTime).format('YYYY-MM-DD HH:mm:ss') : '',
    };
    dialogTitle.value = "编辑数据";
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error("获取详情失败");
  }
};

// 处理查看
const handleView = async (row: any) => {
  try {
    const res = await getBridgeMaintenanceRecordById(row.id);
    form.value = {
      ...res.data,
      bridgeName: bridgeOptions.value.find((item) => item.value === Number(row.bridgeId))?.label,
      maintenanceTime: res.data.maintenanceTime ? dayjs(res.data.maintenanceTime).format('YYYY-MM-DD HH:mm:ss') : '',
    };
    dialogTitle.value = "查看详情";
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error("获取详情失败");
  }
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认删除该条数据吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      await deleteBridgeMaintenanceRecord(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }
  ElMessageBox.confirm("确认删除选中的数据吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      await Promise.all(
        selectedRows.value.map((row) => deleteBridgeMaintenanceRecord(row.id))
      );
      ElMessage.success("批量删除成功");
      getList();
    } catch (error) {
      ElMessage.error("批量删除失败");
    }
  });
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const submitForm = {
          ...form.value,
          maintenanceTime: form.value.maintenanceTime ? dayjs(form.value.maintenanceTime).format('YYYY-MM-DD HH:mm:ss') : '',
        };
        const bridgeNameValue = form.value.bridgeName;

            const potentialNumber = parseFloat(bridgeNameValue);
            if (!isNaN(potentialNumber) && typeof potentialNumber === 'number') {
                submitForm.bridgeId = potentialNumber;
            }
        if (form.value.id) {
          await updateBridgeMaintenanceRecord(submitForm);
          ElMessage.success("修改成功");
        } else {
          await addBridgeMaintenanceRecord(submitForm);
          ElMessage.success("新增成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        ElMessage.error("操作失败");
      }
    }
  });
};

// 显示备注信息
const showRemarks = (row: any) => {
  currentRemarks.value = row.remarks || "暂无备注";
  remarksDialogVisible.value = true;
};

// 表格选择改变
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 分页相关方法
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getList();
};

// 显示问题信息
const showIssues = (row: any) => {
  currentIssues.value = row.mainIssues || "暂无问题记录";
  issuesDialogVisible.value = true;
};

// 显示措施信息
const showMeasures = (row: any) => {
  currentMeasures.value = row.measure || "暂无维护措施";
  measuresDialogVisible.value = true;
};

// 显示报告文件路径
const showReport = (row: any) => {
  currentReport.value = row.reportFilePath || "暂无文件路径";
  reportDialogVisible.value = true;
};

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 100000000,
  dictType: '',
})
// 获取桥梁列表数据
const getBridgeOptions = async () => {
  try {
    const res = await getBridgeList(queryParams.value);
    bridgeOptions.value = res.rows.map((item) => ({
      value: item.id,
      label: item.bridgeName,
    }));
    // 获取桥梁列表后重新获取主数据，确保桥梁名称能正确显示
    console.log(bridgeOptions.value)
    await getList();
  } catch (error) {
    console.error("获取桥梁列表失败:", error);
    ElMessage.error("获取桥梁列表失败");
  }
};

onMounted(() => {
  // 初始化时获取路由参数
  if (route.query.bridgeId) {
    bridgeIdFromRoute.value = route.query.bridgeId as string;
  }
  
  // 先获取桥梁列表，再获取主数据
  getBridgeOptions();
});
// 监听路由参数变化
watch(
  () => route.query.bridgeId,
  (newVal) => {
    if (newVal) {
      bridgeIdFromRoute.value = newVal as string;
    } else {
      bridgeIdFromRoute.value = null;
    }
    getList();
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: hidden;
}

.bridge-health-container {
  padding: 20px;
  flex: 1;
  overflow: auto;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);

  .operation-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    background: var(--el-bg-color-overlay);
    padding: 16px;
    border-radius: 4px;

    .left {
      .page-selector {
        width: 180px;

        :deep(.el-input__wrapper) {
          background-color: transparent;
          box-shadow: none !important;

          &:hover {
            background-color: var(--el-fill-color-light);
          }
        }

        :deep(.el-input__inner) {
          font-size: 16px;
          font-weight: 500;
          color: var(--el-color-primary);
        }

        :deep(.el-select-dropdown__item) {
          &.is-active {
            color: var(--el-color-primary);
            font-weight: bold;
            background-color: var(--el-color-primary-light-9);
          }

          &:hover {
            background-color: var(--el-color-primary-light-9);
          }
        }
      }
    }

    .custom-button {
      margin-left: 10px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
      }
    }
  }

  .custom-table {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    background: var(--el-bg-color-overlay);

    :deep(th) {
      background: var(--el-bg-color-page) !important;
    }

    :deep(.el-table__row) {
      background-color: var(--el-bg-color-overlay);
    }

    .bridge-name {
      color: var(--el-color-primary);
      cursor: pointer;

      &:hover {
        text-decoration: underline;
      }
    }

    .operation-button {
      padding: 0 10px;
      font-size: 14px;

      &.danger {
        color: var(--el-color-danger);
      }

      &:hover {
        opacity: 0.8;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.custom-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    background: var(--el-bg-color-overlay);

    .el-dialog__header {
      background: var(--el-bg-color-page);
      margin: 0;
      padding: 20px;
      border-bottom: 1px solid var(--el-border-color-light);
    }

    .el-dialog__body {
      padding: 30px 20px;
    }

    .el-dialog__footer {
      border-top: 1px solid var(--el-border-color-light);
      padding: 15px 20px;
    }
  }

  .dialog-form {
    :deep(.el-form-item__label) {
      color: var(--el-text-color-regular);
    }

    :deep(.el-input__inner) {
      background-color: var(--el-bg-color-overlay);
      border-color: var(--el-border-color);
      color: var(--el-text-color-primary);
    }
  }
}

// 自定义 Element Plus 组件样式
:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-light);
  --el-table-header-bg-color: var(--el-bg-color-page);
  --el-table-row-hover-bg-color: var(--el-fill-color-light);
}

:deep(.el-button--primary) {
  //   background: var(--el-color-primary);
  //   border-color: var(--el-color-primary);

  &:hover {
    background: var(--el-color-primary-light-3);
    border-color: var(--el-color-primary-light-3);
  }
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 10px;
  background-color: var(--el-fill-color);
  border-color: var(--el-border-color-light);
  color: var(--el-text-color-regular);
}

.ellipsis {
  display: inline-block;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.ellipsis-text {
  cursor: pointer;
  color: var(--el-color-primary);
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  &:hover {
    text-decoration: underline;
    opacity: 0.8;
  }
}
</style>
